package cn.tedu.yl.base.interceptor;

import cn.tedu.yl.base.exception.ServiceException;
import cn.tedu.yl.base.response.JsonResult;
import cn.tedu.yl.base.response.StatusCode;
import cn.tedu.yl.base.response.TokenService;
import io.swagger.models.HttpMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

//拦截器
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //用于判断 OPTIONS 请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }


        if("/doc.html".equals(request.getRequestURI()) || "/swagger-resources".equals(request.getRequestURI())){
            return true;
        }


        String token = request.getHeader("token");
        TokenService tokenService = new TokenService();
        boolean status = tokenService.checkToken(token);

        log.info("拦截器中获取token的值：{}", token);
        System.out.println("返回状态--" + status);
        System.out.println(request.getRequestURI());

        if(!status){
            throw new ServiceException(StatusCode.NOT_LOGIN);
        }

        return true;
    }
}
